// pages/profile_edit/index.js
Page({
  data: {
    // 用户信息
    userInfo: {},
    // 表单数据
    formData: {
      nickName: '',
      realName: '',
      avatarUrl: '',
      phoneNumber: '',
      gender: 0,
      birthday: ''
    },
    // 加密显示的手机号
    encryptedPhoneNumber: '',
    // 性别选项
    genderOptions: ['未知', '男', '女'],
    // 当前日期（用于日期选择器上限）
    currentDate: '',
    // 表单验证状态
    validation: {
      nickName: true,
      realName: true
    },
    // 加载状态
    loading: false,
    // 保存状态
    saving: false,
    // 头像上传状态
    uploading: false
  },

  onLoad(options) {
    // 设置当前日期为日期选择器的上限
    const currentDate = new Date().toISOString().split('T')[0]
    this.setData({
      currentDate: currentDate
    })
    this.loadUserInfo()
  },

  /**
   * 加载用户信息
   */
  async loadUserInfo() {
    try {
      this.setData({ loading: true })
      
      const userInfo = wx.getStorageSync('userInfo')
      if (!userInfo) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        return
      }

      // 初始化表单数据
      const formData = {
        nickName: userInfo.nickName || '',
        realName: userInfo.realName || '',
        avatarUrl: userInfo.avatarUrl || '/images/icons/userAvatar.png',
        phoneNumber: userInfo.phoneNumber || '',
        gender: userInfo.gender || 0,
        birthday: userInfo.birthday || ''
      }

      // 加密显示手机号
      const encryptedPhoneNumber = this.formatEncryptedPhone(userInfo.phoneNumber)

      this.setData({
        userInfo,
        formData,
        encryptedPhoneNumber,
        loading: false
      })

    } catch (error) {
      console.error('加载用户信息失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
      this.setData({ loading: false })
    }
  },

  /**
   * 返回按钮点击
   */
  onNavBack() {
    this.checkUnsavedChanges(() => {
      wx.navigateBack()
    })
  },

  /**
   * 检查未保存的更改
   */
  checkUnsavedChanges(callback) {
    const hasChanges = this.hasFormChanges()
    if (hasChanges) {
      wx.showModal({
        title: '提示',
        content: '您有未保存的更改，确定要离开吗？',
        success: (res) => {
          if (res.confirm) {
            callback()
          }
        }
      })
    } else {
      callback()
    }
  },

  /**
   * 检查表单是否有更改
   */
  hasFormChanges() {
    const { userInfo, formData } = this.data
    return (
      userInfo.nickName !== formData.nickName ||
      userInfo.realName !== formData.realName ||
      userInfo.avatarUrl !== formData.avatarUrl ||
      userInfo.phoneNumber !== formData.phoneNumber ||
      userInfo.gender !== formData.gender ||
      userInfo.birthday !== formData.birthday ||
      JSON.stringify(userInfo.region || []) !== JSON.stringify(formData.region) ||
      userInfo.detail !== formData.detail
    )
  },

  /**
   * 选择头像
   */
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail
    if (avatarUrl) {
      this.setData({
        'formData.avatarUrl': avatarUrl
      })
    }
  },

  /**
   * 昵称输入
   */
  onNicknameInput(e) {
    const value = e.detail.value
    this.setData({
      'formData.nickName': value,
      'validation.nickName': this.validateNickname(value)
    })
  },

  /**
   * 真实姓名输入
   */
  onRealNameInput(e) {
    const value = e.detail.value
    this.setData({
      'formData.realName': value,
      'validation.realName': this.validateRealName(value)
    })
  },

  /**

  /**
   * 性别选择
   */
  onGenderChange(e) {
    const value = parseInt(e.detail.value)
    this.setData({
      'formData.gender': value
    })
  },

  /**
   * 生日选择
   */
  onBirthdayChange(e) {
    this.setData({
      'formData.birthday': e.detail.value
    })
  },



  /**
   * 验证昵称
   */
  validateNickname(value) {
    if (!value || value.trim().length === 0) {
      return false
    }
    if (value.length > 20) {
      return false
    }
    return true
  },

  /**
   * 验证真实姓名
   */
  validateRealName(value) {
    if (!value || value.trim().length === 0) {
      return true // 真实姓名可以为空
    }
    if (value.length > 10) {
      return false
    }
    // 简单的中文姓名验证
    const nameRegex = /^[\u4e00-\u9fa5·]{2,10}$/
    return nameRegex.test(value)
  },


  /**
   * 手机号加密显示
   */
  formatEncryptedPhone(phone) {
    if (!phone || phone.length !== 11) {
      return '未绑定手机号'
    }
    return phone.substring(0, 3) + '****' + phone.substring(7)
  },

  /**
   * 表单验证
   */
  validateForm() {
    const { formData } = this.data
    const validation = {
      nickName: this.validateNickname(formData.nickName),
      realName: this.validateRealName(formData.realName)
    }

    this.setData({ validation })

    // 检查是否所有验证都通过
    return Object.values(validation).every(valid => valid)
  },

  /**
   * 保存资料
   */
  async onSave() {
    if (this.data.saving) return

    // 表单验证
    if (!this.validateForm()) {
      wx.showToast({
        title: '请检查输入信息',
        icon: 'none'
      })
      return
    }

    this.setData({ saving: true })

    try {
      // 上传头像（如果有新头像）
      let avatarUrl = this.data.formData.avatarUrl
      if (avatarUrl && !avatarUrl.startsWith('cloud://') && !avatarUrl.startsWith('/images/')) {
        avatarUrl = await this.uploadAvatar(avatarUrl)
      }

      // 准备更新数据
      const updateData = {
        ...this.data.formData,
        avatarUrl,
        updatedAt: new Date()
      }

      // 调用云函数更新用户信息
      const result = await this.updateUserProfile(updateData)

      if (result.success) {
        // 更新本地存储
        const updatedUserInfo = { ...this.data.userInfo, ...updateData }
        wx.setStorageSync('userInfo', updatedUserInfo)

        wx.showToast({
          title: '保存成功',
          icon: 'success'
        })

        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
      } else {
        throw new Error(result.message || '保存失败')
      }

    } catch (error) {
      console.error('保存资料失败:', error)
      wx.showToast({
        title: error.message || '保存失败',
        icon: 'none'
      })
    } finally {
      this.setData({ saving: false })
    }
  },

  /**
   * 上传头像
   */
  async uploadAvatar(avatarUrl) {
    try {
      this.setData({ uploading: true })

      const fileName = `avatar_${Date.now()}_${Math.random().toString(36).substr(2, 9)}.jpg`
      const cloudPath = `shengyi_miniprogram/users/${fileName}`

      const uploadRes = await new Promise((resolve, reject) => {
        wx.cloud.uploadFile({
          cloudPath: cloudPath,
          filePath: avatarUrl,
          success: resolve,
          fail: reject
        })
      })

      return uploadRes.fileID
    } catch (error) {
      console.error('头像上传失败:', error)
      throw new Error('头像上传失败')
    } finally {
      this.setData({ uploading: false })
    }
  },

  /**
   * 更新用户资料云函数
   */
  async updateUserProfile(updateData) {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'updateUserProfile',
        data: updateData,
        success: res => {
          if (res.result) {
            resolve(res.result)
          } else {
            reject(new Error('云函数返回数据格式错误'))
          }
        },
        fail: error => {
          console.error('云函数调用失败:', error)
          reject(error)
        }
      })
    })
  },

  /**
   * 取消编辑
   */
  onCancel() {
    this.checkUnsavedChanges(() => {
      wx.navigateBack()
    })
  },

  /**
   * 页面卸载时检查未保存更改
   */
  onUnload() {
    // 页面卸载时不需要检查，因为用户已经确认离开
  }
})